/**
 * 配置管理公共混入文件
 */

import { messageTipConfirm, showErrorMsg } from '@/api/utils/pc-message';
import { PAGE_INITIAL_OFFSET, WHETHER_ENABLE, POPUP_TYPE } from '@/utils/constants';
import { first, flatten } from 'lodash-es';
const { SIZE_OFFSET, PAGE_OFFSET, SORT_OFFSET } = PAGE_INITIAL_OFFSET;
const { DISABLED_TITLE, ENABLED_TITLE, ENABLED, DISABLED } = WHETHER_ENABLE;
const {
  NEWLY_ADDED: { type: NEWLY_ADDE_TYPE },
  EDIT: { type: EDIT_TYPE },
} = POPUP_TYPE;
const { NEWLY_ADDED, EDIT } = POPUP_TYPE;
export default {
  data() {
    return {
      //新增弹窗
      NEWLY_ADDED,
      //编辑弹窗
      EDIT,
      // 分页事件处理方法集合
      paginationChange: {
        'current-change': this.pageChange,
        'size-change': this.sizeChange,
      },
      rowConfig: {
        //启动拖拽排序
        drag: true,
        //悬浮高亮
        isHover: true,
      },
      //起始序号
      seqConfig: { startIndex: 0 },
      formAttrs: {
        // 显示必填的星号
        'hide-required-asterisk': false,
      },
      //新增、编辑弹窗
      dialogFormVisible: false,
      //表单弹窗类型
      formType: NEWLY_ADDE_TYPE,
      //表格数据
      tableData: [],
      // 表格数据加载状态
      loading: false,
    };
  },
  mounted() {
    /**
     * 获取表格信息
     */
    this.getPageData();
  },
  methods: {
    /**
     * 切换每页条数
     * @param {Number} sizeNumber  每页条数
     */
    sizeChange(sizeNumber) {
      this.pageSize = sizeNumber;
      this.getPageData();
    },

    /**
     * 拖拽排序
     */
    async rowDragendEvent() {
      // 获取当前页数据（包含拖拽后的顺序）
      const currentData = this.$refs.tableRef.getTableData().fullData;
      const startIndex = this.seqConfig.startIndex;
      const params = currentData.map((item, index) => ({
        order: startIndex + SORT_OFFSET + index,
        id: item.id,
      }));
      try {
        //更新排序
        await this.sortList(params);
        //获取表格数据
        this.getPageData();
        this.$message.success('排序成功');
      } catch (error) {
        showErrorMsg(error);
      }
    },

    /**
     * 编辑详情
     * @param {Object} row 编辑的行数据
     */
    editDetails(row) {
      this.getDeetsConfigDetail(row);
      Object.assign(this, {
        dialogFormVisible: true,
        formType: EDIT_TYPE,
      });
    },

    /**
     * 是否启用格式化
     * @param {Object} cellValue 是否启用
     */
    formatterWhetherEnable({ cellValue }) {
      return cellValue ? ENABLED_TITLE : DISABLED_TITLE;
    },

    /**
     * 新增
     */
    handleAdd() {
      Object.assign(this, {
        dialogFormVisible: true,
        formType: NEWLY_ADDE_TYPE,
      });
      //重置表单校验和表单数据
      this.$nextTick(() => {
        this.$refs.increaseForm.clearValidate();
        this.resetForm();
      });
    },

    /**
     * 删除配置
     * @param {Object} params 删除的参数
     */
    deletePageData(params) {
      messageTipConfirm('确认删除该记录?', async () => {
        try {
          await this.deleteList(params);
          this.$message.success('删除成功');
          this.getPageData();
        } catch (error) {
          showErrorMsg(error);
        }
      });
    },

    /**
     * 切换分页
     * @param { number } page 当前页码
     */
    pageChange(page) {
      this.pageNumber = page;
      // 计算开始索引
      this.seqConfig.startIndex = (page - PAGE_OFFSET) * this.pageSize;
      this.getPageData();
    },

    /**
     * 提交表单
     * @param params 表单数据
     */
    submitFormData(params) {
      this.$refs.increaseForm.validate(async (valid, error) => {
        if (!valid) {
          this.$message.error(first(flatten(Object.values(error))).message);
          return;
        }
        try {
          const { addList, updateList, formType } = this;
          const saveFn = formType === NEWLY_ADDE_TYPE ? addList : updateList;
          await saveFn(params);
          this.$message.success('新增成功');
          this.dialogFormVisible = false;
          //重置表单
          this.resetForm();
          //获取表格信息
          this.getPageData();
        } catch (error) {
          showErrorMsg(error);
        }
      });
    },

    /**
     * 获取表格数据
     */
    async getPageData() {
      try {
        const {
          pageSize,
          pageNumber,
          searchParams: { normativeType, year },
        } = this;
        this.loading = true;
        const {
          data: {
            data: { records, total },
          },
        } = await this.getTable({ size: pageSize, page: pageNumber, ...{ normativeType, year } });
        Object.assign(this, {
          tableData: records,
          total: total,
        });
      } catch (error) {
        showErrorMsg(error);
      } finally {
        this.loading = false;
      }
    },
  },
};
